<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  type DataTableColumns,
  NDataTable,
  useMessage
} from 'naive-ui'
import { reactive, ref, shallowRef, onMounted } from 'vue'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination } from '@/utils/http'
import type { CollectingDJTableRowModel } from '@/api/batch'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const message = useMessage()

const submitLoading = ref(false)
const handleSubmit = async () => {
  if (submitLoading.value) return

  try {
    if (!checkedIds.value.length) throw new Error('请选择征集品')
    submitLoading.value = true
    const [error, res] = await sendRequest({
      module: 'batch',
      api: 'clickConfirm',
      override: {
        data: {
          subItems: subItems.value.map((item) => ({
            ...item,
            batchId: route.params.id
          }))
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    message.success(res.msg)
    window.flags.flushBatch = true
    routeReplace()
  } catch (error: any) {
    message.error(error.message)
  } finally {
    submitLoading.value = false
  }
}

const formData = reactive({
  itemName: null
})
const checkedIds = ref<number[]>([])
const subItems = shallowRef<CollectingDJTableRowModel[]>([])
const handleUpdateCheckedIds: any = (_: any, rows: CollectingDJTableRowModel[]) => {
  subItems.value = rows.filter((e) => !e.subItems)
  checkedIds.value = subItems.value.map((e) => e.subItemId)
}
const tableData = ref<CollectingDJTableRowModel[]>([])
const tableLoading = ref(false)
const columns: DataTableColumns<CollectingDJTableRowModel> = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (e, index) => {
      if (!e.subItems) return null
      return index + 1
    }
  },
  {
    title: '征集品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '所属线索',
    key: 'clueName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: '征集方式',
    key: 'collectType'
  },
  {
    title: '点交状态',
    key: 'djStatus'
  }
]
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<CollectingDJTableRowModel>>({
      module: 'batch',
      api: 'collectingDJList',
      override: {
        params: {
          batchId: route.params.id,
          itemName: formData.itemName || null,
          type: 2,
          limit: 10000000
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    res.data.list.forEach((e) => (e.subItemId = e.itemId))
    res.data.list.forEach((e) => (e.subItemCode = e.itemCode))
    tableData.value = res.data.list
    checkedIds.value = []
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}

const totalCount = ref('/')
const queryTotalCount = async () => {
  try {
    const [error, res] = await sendRequest({
      module: 'batch',
      api: 'clickConfirmNum',
      override: {
        params: {
          batchId: route.params.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    totalCount.value = res.data
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  queryTableData()
  queryTotalCount()
})
</script>

<template>
  <div class="dj-confirm">
    <div class="dj-confirm-title">点交确认（共{{ totalCount }}件征集品）</div>
    <NForm
      label-placement="left"
      inline
      :show-feedback="false"
      class="dj-confirm-card"
      style="margin-bottom: 15rem"
      @keydown.enter="queryTableData"
    >
      <NFormItem label="征集品名称：">
        <NInput
          placeholder="请输入征集品名称"
          v-model:value="formData.itemName"
          clearable
        />
      </NFormItem>
      <NButton
        color="#5FB17F"
        @click="queryTableData"
        ghost
      >
        查询
      </NButton>
    </NForm>

    <NDataTable
      :loading="tableLoading"
      :data="tableData"
      :columns="columns"
      children-key="subItems"
      :row-key="(row) => row.subItemId"
      :checked-row-keys="checkedIds"
      @update-checked-row-keys="handleUpdateCheckedIds"
      flex-height
      style="flex: 1"
      class="dj-confirm-card"
    />
  </div>

  <FixedAction>
    <div class="dj-confirm-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.dj-confirm {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  padding: 15rem 0 110rem;
  background-color: #f0efee;

  :deep(.n-data-table__pagination) {
    justify-content: flex-start;
  }

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .dj-confirm-card {
    padding: 20rem;
    background-color: #e1e1e1;
  }

  .n-form.grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rem 60rem;
  }

  .dj-confirm-title {
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }

  .dj-confirm-count {
    display: flex;
    justify-content: center;
    gap: 0 16rem;
    background-color: #e1e1e1;

    &__item {
      display: grid;
      gap: 10rem 17rem;
      justify-content: center;
      grid-template-areas:
        'icon count'
        'icon label';
      flex: 1;
      padding: 18rem;
      background-color: #ebeceb;

      strong {
        font-size: 24rem;
      }

      img {
        display: block;
        grid-area: icon;
        width: 48rem;
        height: 48rem;
        margin-bottom: 10rem;
        align-self: end;
      }

      span:first-of-type {
        grid-area: count;
      }

      span:last-of-type {
        grid-area: label;
      }
    }
  }
}

.dj-confirm-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}
</style>
